const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
import bodyparser from 'koa-bodyparser'
import cors from 'koa2-cors'
import mongoose from 'mongoose'
import session from 'koa-generic-session'
import Reids from 'koa-redis'

import dbConfig from './dbs/config'
import { listen } from './interface/utils/web_scoket'
listen()
import passport from './interface/utils/passport'
// 接口路由
import users from './interface/users'
import studentList from './interface/student'
import towerList from './interface/tower'
import damageUp from './interface/damageUp'
import visitDorm from './interface/visitDorm'
import dormInspect from './interface/dormInspect'

// 解决跨域
app.use(cors())
//  用作于session加密处理
app.keys = ['house', 'keyskeys']
app.proxy = true
app.use(session({
  key: 'house',
  // 为了好识别以后的cookie
  prefix: 'house:uid',
  // 使用redis存储session
  store: new Reids()
}))
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
// 连接mongoose
mongoose.connect(dbConfig.dbs, {
  useNewUrlParser: true
})
// 会在请求周期ctx对象挂载以下方法与属性
//   ctx.state.user 认证用户
//   ctx.login(user) 登录用户（序列化用户）
//   ctx.isAuthenticated() 判断是否认证
// 这里序列化指的是把用户对象存到session里，反序列化就是反过来，从session里取用户数据成对象
app.use(passport.initialize())
app.use(passport.session())

app.use(require('koa-static')(__dirname + '/public'))
// 判断是否带有请求头authorization的token
app.use(async (ctx, next) => {
  // console.log(ctx.request.url)
  // let params =Object.assign({}, ctx.request.query, ctx.request.body);
  // ctx.request.header = {'authorization': "Bearer " + (params.token || '')}
  if (ctx.request.url === '/users/signin'
    || ctx.request.url === '/users/signup'
    || ctx.request.url === '/users/verify') {
    await next();
  } else if (!ctx.header.authorization) {
    return
  } else {
    let studentNum = ctx.header.authorization.split(' ')[0]
    let Ctoken = ctx.header.authorization.split(' ')[1]
    let token = await new Reids().client.hget(`usertoken:${studentNum}`, 'token')
    if (token === Ctoken) {
      await next();
    } else {
      return
    }
  }
})

// 路由地址
app.use(users.routes()).use(users.allowedMethods())
app.use(studentList.routes()).use(studentList.allowedMethods())
app.use(towerList.routes()).use(towerList.allowedMethods())
app.use(damageUp.routes()).use(damageUp.allowedMethods())
app.use(visitDorm.routes()).use(visitDorm.allowedMethods())
app.use(dormInspect.routes()).use(dormInspect.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
